package com.moss.framework.aspectj;

import com.alibaba.fastjson2.JSONArray;
import com.moss.common.annotation.AuthorizationPerm;
import com.moss.common.constant.RedisConstants;
import com.moss.common.exception.ServiceException;
import com.moss.common.exception.URIPermissionException;
import com.moss.common.util.RedisCache;
import com.moss.common.util.ServletUtil;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author gxcc3
 * @date: 2024/8/5 23:59
 * 拦截注解
 */
@Aspect
@Component
public class AuthorizationPermAspect {

    @Resource
    RedisCache redisCache;


    /**
     * 处理请求前执行
     */
    @Before(value = "@annotation(perm)")
    public void boBefore(JoinPoint joinPoint, AuthorizationPerm perm)
    {
        HttpServletRequest request = ServletUtil.getRequest();
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)){
            throw new ServiceException("token为空");
        }
        String permsKey = RedisConstants.USER_PERMS_KEY+token;
        String cacheStr = redisCache.getCacheObject(permsKey);
        List<String> list = JSONArray.parseArray(cacheStr, String.class);
        if (StringUtils.isEmpty(perm.value())){
            return;
        }
        if (list == null || list.isEmpty()){
            throw new URIPermissionException("接口未授权");
        }
        if (!list.contains(perm.value())){
            throw new URIPermissionException(String.format("接口无权限 - URI - [%s]",request.getRequestURI()));
        }
    }
}
